#!/usr/bin/env bash
cd ~/.config/eww

volicons=("" "" "")
XDG_CACHE_HOME="$HOME/.cache"
date="$XDG_CACHE_HOME/eww/osd_vol.date"
lock=0

showhide() {
  # get dates
  rundate=$(cat "$date")
  currentdate=$(date +%s)

  # handle showing
  if [ "$rundate" = "$currentdate" ] && [ "$lock" -eq 0 ]; then
    scripts/toggle-osd-vol.sh --open
    lock=1
  elif [ $((currentdate - rundate)) -ge 2 ] && [ "$lock" -eq 1 ]; then
    scripts/toggle-osd-vol.sh --close > /dev/null
    lock=0
  fi
}

osd() {
  if [ ! -f "$date" ]; then
    mkdir -p "$XDG_CACHE_HOME/eww"
  fi
  date +%s > "$date"
  showhide
}

osd_handler() {
  lock=0
  rundate=0
  if [ ! -f "$date" ]; then
    mkdir -p "$XDG_CACHE_HOME/eww"
    echo 0 > "$date"
  fi

  while true; do
    showhide
    sleep 0.1
  done
}

vol() {
  pamixer --get-volume
}
ismuted() {
  pamixer --get-mute
}
setvol() {
  pamixer --set-volume $1
}
setmute() {
  pamixer --toggle-mute
}

if [ "$1" = "--once" ]; then
  lvl=$(awk -v n="$(vol)" 'BEGIN{print int(n/34)}')
    ismuted=$(ismuted)

    if [ "$ismuted" ]; then
    	icon="${volicons[$lvl]}"
    else
      icon=""
    fi
    audio=1
    if [ "$(pamixer --get-volume-human | grep 'muted')" == "" ]; then
      audio=1
    else 
      audio=0
    fi

    echo '{"icon":"'"$icon"'","audio":"'"$audio"'","percent":"'"$(vol)"'","microphone":"'"$(vol)"'"}'
    exit 0
fi

if [ "$1" = "mute" ]; then
  setmute
elif [ "$1" = "setvol" ]; then
  setvol "$2"
elif [ "$1" = "osd" ]; then
  osd
else
  # initial values
  lvl=$(awk -v n="$(vol)" 'BEGIN{print int(n/34)}')
  ismuted=$(ismuted)

  if [ "$ismuted" ]; then
  	icon="${volicons[$lvl]}"
  else
    icon=""
  fi
  audio=1
  if [ "$(pamixer --get-volume-human | grep 'muted')" == "" ]; then
    audio=1
  else 
    audio=0
  fi

  echo '{"icon":"'"$icon"'","audio":"'"$audio"'","percent":"'"$(vol)"'","microphone":"'"$(vol)"'"}'

  osd_handler &
  # event loop
  pactl subscribe | rg --line-buffered "on sink" | while read -r _; do
    lvl=$(awk -v n="$(vol)" 'BEGIN{print int(n/34)}')
    ismuted=$(ismuted)

    if [ "$ismuted" ]; then
    	icon="${volicons[$lvl]}"
    else
      icon=""
    fi
    audio=1
    if [ "$(pamixer --get-volume-human | grep 'muted')" == "" ]; then
      audio=1
    else 
      audio=0
    fi

    echo '{"icon":"'"$icon"'","audio":"'"$audio"'","percent":"'"$(vol)"'","microphone":"'"$(vol)"'"}'
  done
fi
